import React, { useState, useEffect } from "react"
import styled from "styled-components"
import Logout from "./Logout"
import ChatInput from "./ChatInput"
import Messages from "./Messages"
import { toast } from "react-toastify"
import { sendMessageRoute, getAllMessageRoute } from "../utils/APIRoutes"
import axios from "axios"

export default function ChatContainer({ currentChat, currentUser, socket }) {
  const [currentChatName, setCurrentChatName] = useState(undefined)
  const [currentChatImage, setCurrentChatImage] = useState(undefined)
  const [messages, setMessages] = useState([])
  const [arrivalMessage, setArrivalMessage] = useState(null)

  const toastOptions = {
    position: "bottom-right",
    autoClose: 5000,
    pauseOnHover: true,
    draggable: true,
    hideProgressBar: true,
    theme: "dark",
  }

  useEffect(() => {
    if (currentChat) {
      setCurrentChatName(currentChat.username)
      setCurrentChatImage(currentChat.avatarImage)

      axios
        .post(getAllMessageRoute, {
          from: currentUser._id,
          to: currentChat._id,
        })
        .then((res) => {
          setMessages(res.data.projectMessages)
        })
        .catch(() => {
          toast.error("Unknown error.", toastOptions)
        })
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentChat])

  const handleSendMessage = async (message) => {
    let sendRes = false
    await axios
      .post(sendMessageRoute, {
        from: currentUser._id,
        to: currentChat._id,
        message: message,
      })
      .then((res) => {
        if (res.data.status) {
          sendRes = true
          socket.current.emit("send-msg", {
            from: currentUser._id,
            to: currentChat._id,
            message: message,
          })
          setMessages((prev) => [...prev, { fromSelf: true, message: message }])
        } else {
          toast.error(res.data.msg, toastOptions)
        }
      })
      .catch(() => {
        toast.error("Unknown error.", toastOptions)
      })
    return sendRes
  }

  useEffect(() => {
    if (socket.current) {
      socket.current.on("msg-recieve", (message) => {
        setArrivalMessage(message)
      })
    }
  }, [socket])

  useEffect(() => {
    arrivalMessage &&
      setMessages((prev) => [
        ...prev,
        { fromSelf: false, message: arrivalMessage },
      ])
  }, [arrivalMessage])

  return (
    <Container>
      <div className="chat-header">
        <div className="user-details">
          <div className="avatar">
            {currentChatImage && (
              <img
                src={`data:image/svg+xml;base64,${currentChatImage}`}
                alt="avatar"
              />
            )}
          </div>
          <div className="username">
            <h3>{currentChatName}</h3>
          </div>
        </div>
        <Logout />
      </div>
      <Messages messages={messages} />
      <ChatInput handleSendMessage={handleSendMessage} />
    </Container>
  )
}

const Container = styled.div`
  padding-top: 1rem;
  display: grid;
  grid-template-rows: 10% 78% 12%;
  gap: 0.1rem;
  overflow: hidden;

  .chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 2rem;
    .user-details {
      display: flex;
      align-items: center;
      gap: 1rem;
      .avatar {
        img {
          height: 3rem;
        }
      }
      .username {
        h3 {
          color: white;
        }
      }
    }
  }
`
